package com.yeyaomai.dksns.flowis.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.yeyaomai.dksns.flowis.domain.Engine;
import com.yeyaomai.dksns.flowis.domain.EngineKeyword;
import com.yeyaomai.dksns.flowis.domain.Keyword;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisQueryOrder;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisStatDetailDTO;
import com.yeyaomai.dksns.flowis.service.DownExcelService;
import com.yeyaomai.dksns.flowis.service.EngineService;
import com.yeyaomai.dksns.flowis.service.KeywordService;
import com.yeyaomai.dksns.flowis.service.result.EngineXml;
import com.yeyaomai.dksns.flowis.util.CollectionNames;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

/**
 * 搜索引擎Controller
 * 
 */

@Controller
@RequestMapping("/source/*")
public class EngineKeywordController {
	
	@Resource
	private EngineService engineService;
	
	@Autowired
	private KeywordService keywordService;
	
	@Autowired
	DownExcelService  downExcelService;
	
	
	//搜索引擎详细信息列表统计
	@RequestMapping(method = RequestMethod.GET, value = "/search-count")
	public String searchCount(HttpServletRequest request,
			HttpServletResponse httpResponse, FlowisQueryOrder order,
			ModelMap modelMap){
		
		order.setStartTime(request.getParameter("startTime") != null ? request
				.getParameter("startTime") : VelocityToolDateUtils.getDay(0));
		order.setEndTime(request.getParameter("endTime") != null ? request
				.getParameter("endTime") : VelocityToolDateUtils.getDay(0));
		String type = request.getParameter("type") != null ? request.getParameter("type") : "1";
		
		List<Engine> engineList=engineService.getEngineByDate(order.getStartTime(), order.getEndTime());
		
		Long searchCount_total =0l;
		if(engineList != null) {
			
			List<EngineKeyword> engineKeywords = new ArrayList<EngineKeyword>(); 
			for (Engine engine : engineList) {
				
				searchCount_total +=engine.getSearchCount();
				engineKeywords = engineService.getEngineKeywordByEngineDate(engine.getEngineName(), order.getStartTime(), order.getEndTime());
				engine.setKeywordNumber(engineKeywords.size());
				engine.setEngineKeywords(engineKeywords);
			}
			
		}
		
		modelMap.addAttribute("engines", engineList);
		modelMap.addAttribute("order", order);
		modelMap.addAttribute("searchCount_total", searchCount_total);
		modelMap.addAttribute("type", type);
		return "search-count";
	}
	
	//搜索关键字
	@RequestMapping(method = RequestMethod.GET, value = "/search-word")
	public String keywordEngine(HttpServletRequest request,
			HttpServletResponse httpResponse, FlowisQueryOrder order,
			ModelMap modelMap) {

		order.setStartTime(request.getParameter("startTime") != null ? request
				.getParameter("startTime") : VelocityToolDateUtils.getDay(0));
		order.setEndTime(request.getParameter("endTime") != null ? request
				.getParameter("endTime") : VelocityToolDateUtils.getDay(0));
		String type = request.getParameter("type") != null ? request.getParameter("type") : "1";
		
		Page<Keyword> kwPage  = keywordService.getSplit(order);
		
		if(kwPage.getContent() != null) {
			
			List<EngineKeyword> engineKeywords = new ArrayList<EngineKeyword>(); 
			for (Keyword keyword : kwPage.getContent()) {
				
				engineKeywords = keywordService.getEngineKeywordByKeywordDate(keyword.getKeyword(), order.getStartTime(), order.getEndTime());
				if(engineKeywords.size()!=0){
					keyword.setEngineKeywords(engineKeywords);
				}
			}
		}
		
		modelMap.addAttribute("kwPage", kwPage);
		modelMap.addAttribute("order", order);
		modelMap.addAttribute("type", type);
		return "search-word";

	}

	@RequestMapping(value = "/search-lately")
	public String lately(HttpServletRequest request,HttpServletResponse response, FlowisQueryOrder order,
			ModelMap modelMap) {
		
		order.setStartTime(request.getParameter("startTime") != null ? request
				.getParameter("startTime") : VelocityToolDateUtils.getDay(0));
		order.setEndTime(request.getParameter("endTime") != null ? request
				.getParameter("endTime") : VelocityToolDateUtils.getDay(1));
		
	    Page<FlowisStatDetailDTO>  result=	keywordService.getSplitLately(order);
		modelMap.addAttribute("result", result);
		modelMap.addAttribute("order", order);
		
	    return  "search-lately";
		
	}

	@RequestMapping(value = "pie")
	public void pieXml(@RequestParam("startTime") String startTime,
			@RequestParam("endTime") String endTime, HttpServletResponse response)
			throws IOException {	
		
		List<Engine> engineList=engineService.getEngineByDate(startTime, endTime);
		String xml=EngineXml.getPie(engineList, startTime, endTime);
		
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml); 
		
	}

	//总搜索量近30日趋势 
	@RequestMapping(value="stackedArea")
	public void stackedAreaXml(HttpServletResponse response) throws IOException{ 
		
		String st =  VelocityToolDateUtils.getDay(-29);
		String et = VelocityToolDateUtils.getDay(0);
		
		Map<String, Long> searchCountMap = countEngine(engineService.getSearchCountByDate(st, et));
		
		String xml=EngineXml.getArea(searchCountMap);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}
	
	
	//主要搜索引擎搜索量近30日趋势
	@RequestMapping(value="msLine")
	public void msLineXml(HttpServletResponse response) throws IOException{ 
		
		String st =  VelocityToolDateUtils.getDay(-29);
		String et = VelocityToolDateUtils.getDay(0);
		
		Map<String, Long> baiduMap = countEngine(engineService.getEngineByEngineDate(CollectionNames.BAIDU, st, et));
		Map<String, Long> sougouMap = countEngine(engineService.getEngineByEngineDate(CollectionNames.SOUGOU, st, et));
		Map<String, Long> gugeMap =  countEngine(engineService.getEngineByEngineDate(CollectionNames.GUGE, st, et));
		
		
		String xml=EngineXml.getLine(baiduMap,sougouMap,gugeMap);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(xml);
	}
	
	
	private Map<String, Long> countEngine(List<Engine> engineList){
		
		List<Map.Entry<String, String>> entryMap=VelocityToolDateUtils.getThirtyday();
		Map<String, Long> engineMap=new TreeMap<String, Long>();
		
		//搜索List中对应数据 
		for(Map.Entry<String, String> entry : entryMap){
			
			Boolean isNull = true;
			for (Engine engine : engineList) {
				if(VelocityToolDateUtils.formatperiod.format(engine.getDate()).equals(entry.getValue())){
					engineMap.put(entry.getValue(), Long.valueOf(engine.getSearchCount()));
					isNull = false;
				} 
			}
			if(isNull){
				engineMap.put(entry.getValue(), 0l);
			}
		}
		return engineMap;
	}
	
	
	//搜索引擎报表下载
	@RequestMapping(value="downCount")
	public void downCount(HttpServletRequest request,HttpServletResponse response, 
			FlowisQueryOrder order) throws UnsupportedEncodingException {
		
		order.setStartTime(request.getParameter("startTime") != null ? request
				.getParameter("startTime") : VelocityToolDateUtils.getDay(0));
		order.setEndTime(request.getParameter("endTime") != null ? request
				.getParameter("endTime") : VelocityToolDateUtils.getDay(0));
		
		List<Engine> engineList=engineService.getEngineByDate(order.getStartTime(), order.getEndTime());
		Long searchCount_total =0l;
		if(engineList != null) {
			
			for (Engine engine : engineList) {
				searchCount_total +=engine.getSearchCount();
				engine.setKeywordNumber(engineService.getEngineKeywordByEngineDateCount(engine.getEngineName(), order.getStartTime(), order.getEndTime()));
			}
			
		}
		
    	String title = "搜索引擎("+order.getStartTime()+"至"+order.getEndTime()+")";
    	String newTitle = URLEncoder.encode(title, "UTF-8"); 

	    response.setContentType("application/vnd.ms-excel");
	    response.setHeader("Content-disposition", "attachment;filename=" + newTitle+".xls");   
	    
	    List<String>  heads  =new ArrayList<String>();
	    heads.add("搜索引擎");
	    heads.add("关键字个数");
	    heads.add("搜索次数");
	    heads.add("独立访客");
	    heads.add("IP");
	    
	    List<String> pros =new ArrayList<String>();
	    pros.add("engineName");
	    pros.add("keywordNumber");
	    pros.add("searchCount");
	    pros.add("uniqueVisitors");
	    pros.add("ip");
	    
	    try {
			downExcelService.exportExcel(title, heads, engineList, response.getOutputStream(), pros);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	//搜索关键字报表下载
	@RequestMapping(value="downWord")
	public void downWord(HttpServletRequest request,HttpServletResponse response, 
			FlowisQueryOrder order) throws UnsupportedEncodingException {
		
		order.setStartTime(request.getParameter("startTime") != null ? request
				.getParameter("startTime") : VelocityToolDateUtils.getDay(0));
		order.setEndTime(request.getParameter("endTime") != null ? request
				.getParameter("endTime") : VelocityToolDateUtils.getDay(0));
		
		
		List<Keyword> keywordList  = keywordService.getKeywordByDate(order.getStartTime(), order.getEndTime());
		
    	String title = "搜索关键字("+order.getStartTime()+"至"+order.getEndTime()+")";
    	String newTitle = URLEncoder.encode(title, "UTF-8"); 

	    response.setContentType("application/vnd.ms-excel");
	    response.setHeader("Content-disposition", "attachment;filename=" + newTitle+".xls");   
	    
	    List<String>  heads  =new ArrayList<String>();
	    heads.add("关键词");
	    heads.add("搜索次数");
	    heads.add("独立访客");
	    heads.add("IP");
	    heads.add("新独立访客");
	    
	    List<String> pros =new ArrayList<String>();
	    pros.add("keyword");
	    pros.add("searchCount");
	    pros.add("uniqueVisitors");
	    pros.add("ip");
	    pros.add("newUniqueVisitors");
	    
	    try {
			downExcelService.exportExcel(title, heads, keywordList, response.getOutputStream(), pros);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	//最近搜索报表下载
	@RequestMapping(value="downLately")
	public void downLately(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		
		String st  = VelocityToolDateUtils.getDay(0);
		String et = VelocityToolDateUtils.getDay(1);
		
	    List<FlowisStatDetailDTO>  result=	keywordService.getSearchLately(st, et);
		
    	String title = "最近搜索("+st+")";
    	String newTitle = URLEncoder.encode(title, "UTF-8"); 

	    response.setContentType("application/vnd.ms-excel");
	    response.setHeader("Content-disposition", "attachment;filename=" + newTitle+".xls");   
	    
	    List<String>  heads  =new ArrayList<String>();
	    heads.add("时间");
	    heads.add("IP");
	    heads.add("引擎");
	    heads.add("关键字");
	    heads.add("地理位置-省");
	    heads.add("地理位置-市");
	    heads.add("停留页面");
	    
	    
	    List<String> pros =new ArrayList<String>();
	    pros.add("access_date");
	    pros.add("ip");
	    pros.add("engineName");
	    pros.add("keyword");
	    pros.add("access_province");
	    pros.add("access_city");
	    pros.add("access_url");
	    
	    try {
			downExcelService.exportExcel(title, heads, result, response.getOutputStream(), pros);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
